<?php


namespace Agoni\MeiTuan;
use GuzzleHttp;
use Agoni\DispatchException;
use Agoni\Api;
class ApiRequest implements Api
{

    /**
     * @var string
     */
    private $appKey;

    /**
     * @var string
     */
    private $secret;

    protected $Api = 'https://peisongopen.meituan.com/api/';

    public function __construct(string $appKey, string $secret)
    {
        $this->appKey = $appKey;
        $this->secret = $secret;
    }

    /**
     * @param string $method
     * @param array $params
     * @return mixed
     * @throws DispatchException
     */
    public function request($url, array $params,$method="post")
    {

        $params = array_merge($params, [
            'appkey' => $this->appKey,
            'timestamp' => time(),
            'version' => '1.0',
        ]);

        $params['sign'] = $this->signature($params);

        $client=new GuzzleHttp\Client();
        $data['json']=$params;

        $res=$client->request($method,$this->Api.$url,$data);
        $results=$res->getBody()->getContents();

        print_r($results);die;
//        print_r($params);die;
//
//        $http = $this->getHttp();
//
//        $response = $http->post(self::URL . $method, $params);
//
//        $result = json_decode(strval($response->getBody()), true);
//
//        $this->checkErrorAndThrow($result);

        return $result;
    }

    public function signature(array $params)
    {
        ksort($params);

        $waitSign = '';
        foreach ($params as $key => $item) {
            if ($item) {
                $waitSign .= $key.$item;
            }
        }

        return strtolower(sha1($this->secret.$waitSign));
    }

    /**
     * @param $result
     * @throws DispatchException
     */
    public function checkErrorAndThrow($result)
    {
        if (!$result || $result['code'] != 0) {
            throw new DispatchException($result['message'], $result['code']);
        }
    }
}